#!/bin/bash
{
	#////////////////////////////////////
	# DietPi Survey Script
	#
	#////////////////////////////////////
	# Created by Daniel Knight / daniel.knight@dietpi.com / dietpi.com
	#
	#////////////////////////////////////
	#
	# Info:
	# - Allows to send DietPi usage info via SFTP to DietPi server
	# - Includes hardware info, DietPi version+branch, installed software, benchmark results and some setup info
	# - No private data is sent, no one can indentify you.
	# - Runs after every dietpi-update and dietpi-software install, if user opted in
	# - Summary can be visited at: https://dietpi.com/survey/
	# - Allows the DietPi project to focus development based on popularity
	# - Further info: https://dietpi.com/docs/dietpi_tools/#dietpi-survey
	#
	# Usage:
	# - /boot/dietpi/dietpi-survey		Interactive menu to opt in or out
	# - /boot/dietpi/dietpi-survey 1	Non-interactively send survey data or empty file, based on previous user choice
	#
	# File sent format: $G_HW_UUID.txt
	#////////////////////////////////////

	# Import DietPi-Globals --------------------------------------------------------------
	. /boot/dietpi/func/dietpi-globals
	readonly G_PROGRAM_NAME='DietPi-Survey'
	G_CHECK_ROOT_USER
	G_INIT
	# Import DietPi-Globals --------------------------------------------------------------

	EXIT_CODE=1

	# Grab input
	[[ $1 == 1 ]] && INPUT=1 || INPUT=0

	readonly FP_UPLOAD="$G_HW_UUID.txt"
	readonly SFTP_ADDR='ssh.dietpi.com'
	readonly SFTP_USER='dietpi-survey'
	readonly SFTP_PASS='upload2dietpi'

	Generate_File(){

		# DietPi version
		local version="$G_DIETPI_VERSION_CORE.$G_DIETPI_VERSION_SUB"

		# Current Git owner/branch
		local gitbranch="$G_GITOWNER/$G_GITBRANCH"

		# Active network interface
		local network_interface
		[[ -f '/run/dietpi/.network' ]] && network_interface=$(mawk 'NR==3' /run/dietpi/.network)
		[[ $network_interface ]] || network_interface='NONE'

		# Autostart index
		local autostart_index
		[[ -f '/boot/dietpi/.dietpi-autostart_index' ]] && autostart_index=$(</boot/dietpi/.dietpi-autostart_index)
		[[ $autostart_index ]] || autostart_index=0

		cat << _EOF_ > "$FP_UPLOAD"
#!/bin/bash
((aDIETPI_VERSION[$version]++))
((aGIT_BRANCH[$gitbranch]++))
((aDEVICE_NAME[$G_HW_MODEL_NAME]++))
((aCPU_ARCH[$G_HW_ARCH_NAME]++))
((aCPU_COUNT[$G_HW_CPU_CORES]++))
((aDISTRO_VERSION[$G_DISTRO_NAME]++))
((aAUTOSTART_OPTION[\${aAUTOSTART_NAME[$autostart_index]:=$autostart_index}]++))
((aAUTO_SETUP_AUTOMATED[$(grep -cm1 '^[[:blank:]]*AUTO_SETUP_AUTOMATED=1' /boot/dietpi.txt)]++))
((aNETWORK_INTERFACE[$network_interface]++))
_EOF_

		# RPi: Raspbian/Raspberry Pi OS (32-bt) or Debian/Raspberry Pi OS (64-bit)?
		(( $G_HW_MODEL < 10 )) && echo "((aRASPBIAN[$G_RASPBIAN]++))" >> "$FP_UPLOAD"

		# DietPi-Software installs
		if [[ -f '/boot/dietpi/.installed' ]]; then

			echo -e '# -------------------------\n# DietPi-Software installs\n# -------------------------' >> "$FP_UPLOAD"

			while read -r software
			do

				software=${software##*[}
				software=${software%%]*}
				disable_error=1 G_CHECK_VALIDINT "$software" && echo "((aSOFTWARE[\${aSOFTWARE_NAME${G_DIETPI_VERSION_CORE}_${G_DIETPI_VERSION_SUB}[$software]:=$software}]++))" >> "$FP_UPLOAD"

			done < <(grep ']=2$' /boot/dietpi/.installed)

		fi

		# DietPi-Benchmark results
		[[ -f '/var/lib/dietpi/dietpi-benchmark/results' ]] && cat /var/lib/dietpi/dietpi-benchmark/results >> "$FP_UPLOAD"

	}

	Send_File(){

		if (( $OPTED_IN )); then

			[[ -f $FP_UPLOAD ]] || Generate_File

		else

			# Send empty file to overwrite existing data, rm is not possible due to missing file list permissions
			> "$FP_UPLOAD"

		fi

		# Upload to server
		local timeout=$(sed -n '/^[[:blank:]]*CONFIG_G_CHECK_URL_TIMEOUT=/{s/^[^=]*=//p;q}' /boot/dietpi.txt) G_EXEC_DESC='Sending survey data'
		(( $OPTED_IN )) || G_EXEC_DESC='Purging survey data'
		# - Timeout times 2 for DNS resolving + connection, upload itself is done in no time
		G_EXEC_NOHALT=1 G_EXEC curl -m $(( ${timeout:-5} * 2 )) -sT "$FP_UPLOAD" sftp://$SFTP_USER:$SFTP_PASS@$SFTP_ADDR/survey/
		EXIT_CODE=$?

	}

	#/////////////////////////////////////////////////////////////////////////////////////
	# Main Loop
	#/////////////////////////////////////////////////////////////////////////////////////
	# Read opt in/out choice: 1=yes and send data | 0=no and purge data
	OPTED_IN=$(sed -n '/^[[:blank:]]*SURVEY_OPTED_IN=[01]$/{s/^[^=]*=//p;q}' /boot/dietpi.txt)
	# - No (valid) choice done yet
	if [[ $OPTED_IN != [01] ]]; then

		# Do not send data without user interactively opted in!
		OPTED_IN=0
		# Ask for choice, if interactive
		(( $G_INTERACTIVE )) && INPUT=0

	fi

	# Interactive menu
	until (( $INPUT ))
	do

		G_WHIP_MENU_ARRAY=(

			'Show' ': Show me the upload file content'
			'1' ': Opt IN and upload data'
			'0' ': Opt OUT and purge uploaded data'

		)

		G_WHIP_DEFAULT_ITEM=$OPTED_IN
		if G_WHIP_MENU 'DietPi-Survey would like to collect anonymous usage statistics.
This allows us to focus development based on popularity.
 - NO private data will be collected and NO ONE can identify you based on it.
 - The data is sent via secured SFTP connection, stored unreadable to the public upload user.
 - If you agree, your uploaded data will be updated after each DietPi-Update and DietPi-Software install.
 - Current survey statistics can be reviewed at: https://dietpi.com/survey/
\nWould you like to join DietPi-Survey?'; then

			if [[ $G_WHIP_RETURNED_VALUE == 'Show' ]]; then

				Generate_File
				G_WHIP_VIEWFILE "$FP_UPLOAD"
				continue # Stay in loop

			else

				OPTED_IN=$G_WHIP_RETURNED_VALUE
				G_CONFIG_INJECT 'SURVEY_OPTED_IN=' "SURVEY_OPTED_IN=$OPTED_IN" /boot/dietpi.txt

			fi

		fi

		break

	done

	# Send data if opted in or empty file if opted out
	Send_File

	#-----------------------------------------------------------------------------------
	exit $EXIT_CODE
	#-----------------------------------------------------------------------------------
}
